/*
 * Copyright (c) 2015 Uwantsoft Ltd.
 * www.uwantsoft.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Uwantsoft ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with Uwantsoft.
 */

package com.uwantsoft.util;


import org.springframework.orm.hibernate4.HibernateTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Chuanbao
 */
@SuppressWarnings("unchecked")
public class HibernateEntityRepository implements EntityRepository {

    @Resource
    private HibernateTemplate hibernateTemplate;

    public void save(AbstractEntity entity){
        getHibernateTemplate().save(entity);
    }

    public void update(AbstractEntity entity){
        getHibernateTemplate().update(entity);
    }

    public <T extends AbstractEntity> T findEntityByGuid(String guid,Class<T> clazz){
        List<T> list = (List<T>) getHibernateTemplate().find("from " + clazz.getSimpleName() + " c where c.guid=?", guid);
        return list.isEmpty() ? null : list.get(0);
    }

    public <T extends AbstractEntity> T findByGuid(String guid,Class<T> clazz){
        List<T> list = (List<T>) getHibernateTemplate().find("from " + clazz.getSimpleName() + " c where c.active=true and c.guid=?", guid);
        return list.isEmpty() ? null : list.get(0);
    }

    public void delete(AbstractEntity entity){
        getHibernateTemplate().delete(entity);
    }

    public void deleteAll(List<AbstractEntity> entities){
        getHibernateTemplate().deleteAll(entities);
    }

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }
}
